import logging

import os
import traceback

from app.session import get_token
from config.config import debug, host_name

host = '0.0.0.0'
port = 80 if not debug else 5002


class Log:
    def __init__(self, name):
        self.logger = logging.getLogger(name)
        print(host_name)
        file_name = os.path.join(os.path.split(os.path.realpath(__file__))[0], 'logs',
                                 str(name) + "_" + str(host_name)[:-1] + '.log')
        if not os.path.exists(file_name):
            open(file_name, 'w')

        handler = logging.FileHandler(file_name, encoding='UTF-8')
        log_format = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
        handler.setFormatter(log_format)

        self.logger.addHandler(handler)

        self.b_info = self.logger.info
        self.b_debug = self.logger.debug
        self.b_warning = self.logger.warning
        self.b_error = self.logger.error
        self.b_exception = self.logger.exception

        self.logger.info = self.info
        self.logger.debug = self.debug
        self.logger.warning = self.warning
        self.logger.error = self.error
        self.logger.exception = self.exception

    def info(self, val):
        # print(get_token())
        try:
            msg = "UID=" + "aaa" + ",content=" + val
            print(msg)
            self.b_info(msg)
        except Exception as e:
            print(e)

    def exception(self, val):
        traceback.print_exc()
        self.b_exception(val)

    def debug(self, val):
        try:
            msg = "UID=" + "aaa" + ",content=" + val
            print(msg)
            self.b_debug(msg)
        except Exception as e:
            print(e)

    def warning(self, val):
        try:
            msg = "UID=" + "aaa" + ",content=" + val
            print(msg)
            self.b_warning(msg)
        except Exception as e:
            print(e)

    def error(self, val):
        try:
            msg = "UID=" + "aaa" + ",content=" + val
            print(msg)
            self.b_error(msg)
        except Exception as e:
            print(e)

    def init(self):
        levels = (
            logging.INFO,
            logging.DEBUG
        )
        for level in levels:
            self.logger.setLevel(level)
        return self.logger
